<template>
  <!-- 订货计划表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="850px"
    draggable
    @close="closeDialog"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      style="display: flex"
    >
      <el-row>
        <!-- 工厂号-->
        <el-col :span="12">
          <el-form-item label="工厂" prop="plantId">
            <el-select
              @change="plantChange"
              v-model="formData.plantId"
              placeholder="请选择"
              style="width: 250px"
              :disabled="disabled"
            >
              <el-option
                v-for="item in plants"
                :key="item.id"
                :label="item.organizationCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="partnerId">
            <el-select
              @change="partnerChange"
              v-model="formData.partnerId"
              placeholder="请选择"
              style="width: 250px"
              :disabled="disabled"
            >
              <el-option
                v-for="item in partners"
                :key="item.id"
                :label="item.partnerName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!--物料号-->
        <el-col :span="12">
          <el-form-item label="物料" prop="materialId">
            <el-select
              @change="materialChange"
              v-model="formData.materialId"
              placeholder="请选择"
              style="width: 250px"
              :disabled="disabled"
            >
              <el-option
                v-for="item in materials"
                :key="item.materialId"
                :label="item.materialName"
                :value="item.materialId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!--计划到货日期-->
        <el-col :span="12">
          <el-form-item label="计划到货日期" prop="arriveDate">
            <el-date-picker
              v-model="formData.arriveDate"
              type="date"
              placeholder="请输入到货日期"
              style="width: 250px"
              :disabled-date="disabledDate"
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="卸货口" prop="dischargeHatchId">
            <el-select
              @change="dischargehatchChange"
              v-model="formData.dischargeHatchId"
              placeholder="请选择"
              style="width: 250px"
              :disabled="disabled"
            >
              <el-option
                v-for="item in dischargehatchs"
                :key="item.id"
                :label="item.dischargeHatchCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!--      计划采购数量-->
        <el-col :span="12">
          <el-form-item label="要货数量" prop="planQuantity">
            <el-input-number
              v-model="formData.planQuantity"
              :min="1"
              style="width: 250px"
            />
          </el-form-item>
        </el-col>
        <!--备注-->
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.remarks"
            placeholder="请输入备注"
            type="textarea"
            :rows="2"
            style="width: 655px"
          />
          <span v-else>{{ formData.remarks }}</span>
        </el-form-item>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SRMSRMPLANSCHEDULEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

// 工厂
let plants: any = ref([]);
// 物料号
let materials: any = ref([]);
// 供应商
let partners: any = ref([]);
// 卸货口
let dischargehatchs: any = ref([]);

const disabled = ref(false);

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

// 表单校验规则
const rules = reactive({
  plantId: [{ required: true, message: "未选择工厂", trigger: "change" }],
  partnerId: [{ required: true, message: "未选择供应商", trigger: "change" }],
  arriveDate: [
    {
      required: true,
      type: "date",
      message: "未选择到货日期",
      trigger: "change",
    },
  ],
  materialId: [{ required: true, message: "未选择物料", trigger: "change" }],
  storageLocationName: [
    { required: true, message: "未选择要货地点", trigger: "change" },
  ],
  planQuantity: [
    { required: true, message: "未输入要货数量", trigger: "change" },
  ],
  dischargeHatchId: [
    { required: true, message: "未选择周期类型", trigger: "change" },
  ],
  purchasePlanNumber: [
    { required: true, message: "未选择采购协议", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  beginDate: [],
  endDate: [],
  filename: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  planNo: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  dischargeHatchId: "",
  dischargeHatchCode: "",
  dischargeHatchName: "",
  arriveDate: "",
  arriveYear: "",
  arriveMonth: "",
  arriveWeek: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  planQuantity: 1,
  replyUserId: "",
  replyUserName: "",
  agreeQuantity: "",
  replyTime: "",
  replyContent: "",
  orderScheduleState: "",
  isPacking: "",
  packagingStep: "",
  isExecute: "",
  allowSend: "",
  enabled: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        planNo,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        partnerId,
        partnerCode,
        partnerName,
        dischargeHatchId,
        dischargeHatchCode,
        dischargeHatchName,
        arriveDate,
        arriveYear,
        arriveMonth,
        arriveWeek,
        materialId,
        materialCode,
        materialName,
        planQuantity,
        replyUserId,
        replyUserName,
        agreeQuantity,
        replyTime,
        replyContent,
        orderScheduleState,
        isPacking,
        packagingStep,
        isExecute,
        allowSend,
        enabled,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        planNo,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        partnerId,
        partnerCode,
        partnerName,
        dischargeHatchId,
        dischargeHatchCode,
        dischargeHatchName,
        arriveDate,
        arriveYear,
        arriveMonth,
        arriveWeek,
        materialId,
        materialCode,
        materialName,
        planQuantity,
        replyUserId,
        replyUserName,
        agreeQuantity,
        replyTime,
        replyContent,
        orderScheduleState,
        isPacking,
        packagingStep,
        isExecute,
        allowSend,
        enabled,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      });
      getPlants();
      getPartners();
      getMaterials();
      getDischargehatchs();
      if (formData.id) {
        disabled.value = true;
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.planNo = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.partnerName = "";
  formData.dischargeHatchId = "";
  formData.dischargeHatchCode = "";
  formData.dischargeHatchName = "";
  formData.arriveDate = "";
  formData.arriveYear = "";
  formData.arriveMonth = "";
  formData.arriveWeek = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.planQuantity = 1;
  formData.replyUserId = "";
  formData.replyUserName = "";
  formData.agreeQuantity = "";
  formData.replyTime = "";
  formData.replyContent = "";
  formData.orderScheduleState = "";
  formData.isPacking = "";
  formData.packagingStep = "";
  formData.isExecute = "";
  formData.allowSend = "";
  formData.enabled = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
  disabled.value = false;
}

const loading = ref(false);

// 供应商查询
async function getPartners() {
  const data = await request({
    url: "/mes/core/mdmpartner/getList",
    method: "post",
    data: {},
  });
  partners.value = data.data;
}

// 工厂查询
async function getPlants() {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data;
}

function plantChange() {
  dischargehatchs.value = [];
  formData.dischargeHatchId = "";
  formData.dischargeHatchCode = "";
  formData.dischargeHatchName = "";
  const plan = plants.value.find((item) => {
    return item.id === formData.plantId;
  });
  formData.plantCode = plan.organizationCode;
  formData.plantName = plan.organizationName;
  getDischargehatchs();
}

function partnerChange() {
  materials.value = [];
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  const partner = partners.value.find((item) => {
    return item.id === formData.partnerId;
  });
  formData.partnerCode = partner.partnerCode;
  formData.partnerName = partner.partnerName;
  getMaterials();
}

async function getMaterials() {
  const data = await request({
    url: `/mes/core/partnerproduct/materialList/` + formData.partnerId,
    method: "get",
  });
  materials.value = data.data;
}

function materialChange() {
  const material = materials.value.find((item) => {
    return item.materialId === formData.materialId;
  });
  formData.materialCode = material.materialCode;
  formData.materialName = material.materialName;
}

async function getDischargehatchs() {
  const data = await request({
    url: `/mes/srmdischargehatch/getDropdownList/` + formData.plantId,
    method: "get",
  });
  dischargehatchs.value = data.data;
}

function dischargehatchChange() {
  const dischargehatch = dischargehatchs.value.find((item) => {
    return item.id === formData.dischargeHatchId;
  });
  formData.dischargeHatchCode = dischargehatch.dischargeHatchCode;
  formData.dischargeHatchName = dischargehatch.dischargeHatchName;
}

// 禁用当前日期之前日期(不包含当天日期)
const disabledDate = (time: Date) => {
  return time.getTime() <= Date.now() - 8.64e7;
};

/** 订货计划保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/core/srmplanschedule/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

onMounted(() => {
  getPlants();
  getPartners();
  if (formData.plantId) {
    getDischargehatchs();
  }
  if (formData.partnerId) {
    getMaterials();
  }
});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
